﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using DoubleH.Utility;
using System.Collections.ObjectModel;
using Table=FCNS.Data.Table;
using System.Data;
using FCNS.Data;

namespace StoreS
{
    /// <summary>
    /// PanDian.xaml 的交互逻辑
    /// </summary>
    public partial class PanDian : Window
    {
        enum Flag
        {
            盘点准备单,
            开始盘点
        }

        Flag flag = Flag.盘点准备单;
        ObservableCollection<TempFunction> productInList = new ObservableCollection<TempFunction>();
        Table.CheckStoreS order = null;

        public PanDian()
        {
            InitializeComponent();

            InitEvent();
        }

        public void Init(Table.CheckStoreS obj)
        {
            InitVar();

            dataGridObject.InitColumns(DataTableText.盘点单据商品编辑);
            order = obj ?? new Table.CheckStoreS();
            if (order.Id == -1)
                PanDianReady();
            else
                StartPanDian();

            dataGridObject.ShowBottom = false;
            dataGridObject.ShowBodyContexMenu = false;
            dataGridObject.CanUserAddRows = false;
        }

        private void InitVar()
        {
            uCGroupS1.AutoInsert = false;
            uCGroupS1.IsEditable = true;
            uCUniqueSBrandId.IsEditable = false;
            uCUniqueSPlaceId.IsEditable = false;

            uCGroupS1.Init(FCNS.Data.Table.GroupS.EnumFlag.商品分类);
            uCUniqueSBrandId.Init(FCNS.Data.Table.UniqueS.EnumFlag.品牌);
            uCUniqueSPlaceId.Init(FCNS.Data.Table.UniqueS.EnumFlag.产地);
            uCStoreS1.SelectedObjectId = FCNS.Data.DbDefine.currentStoreSId;
        }

        private void InitEvent()
        {
            panDianReady.Click += (ss, ee) => { PanDianReady(); };
            panDianStart.Click += (ss, ee) =>
            {
                PanDianStart pds = new PanDianStart();
                pds.Init(order);
                pds.ShowDialog();
                if (pds.StartPanDian)
                    StartPanDian();
            };
            panDianEnd.Click += (ss, ee) => { PanDianEnd(); };
            panDianDelete.Click += (ss, ee) => { MessageBox.Show(order.Delete().ToString()); this.Close(); };

            buttonOK.Click += (ss, ee) => { Search(); };
            buttonPrint.Click += (ss, ee) => { Print(); };

            textBoxSearch.KeyDown += (ss, ee) =>
            {
                if (ee.Key == Key.Enter)
                    SearchText();
            };
        }

        private void PanDianReady()
        {
            buttonPrint.Content = "打印";
            uCStoreS1.IsEnabled = true;

            flag = Flag.盘点准备单;
            labelTitle.Content = flag.ToString();

            dataGridObject.IsReadOnly = true;
        }

        private void StartPanDian()
        {
            buttonPrint.Content = "保存";
            uCStoreS1.IsEnabled = false;

            productInList.Clear();
            dataGridObject.ItemsSourceNoCalc = productInList;
            flag = Flag.开始盘点;
            labelTitle.Content = flag.ToString();
         
            StringBuilder sb = new StringBuilder("SELECT  ProductSInCheckStoreS.QuantityOld,ProductSInCheckStoreS.QuantityNew,UniqueS.Name as UnitName,UniqueS1.Name as PlaceName,UniqueS2.Name as BrandName, ProductS.Code, ProductS.Name, ProductS.Standard, ProductS.Barcode,ProductS.Id,ProductS.GroupSId,ProductS.PlaceId,ProductS.BrandId");
            sb.Append(", ProductS.PlaceId FROM ProductS INNER JOIN");
            sb.Append("  ProductSInCheckStoreS ON  ProductS.Id = ProductSInCheckStoreS.ProductSId left join UniqueS on ProductS.UnitId=UniqueS.Id ");
            sb.Append(" left join UniqueS as UniqueS1 on ProductS.PlaceId=UniqueS1.Id left join UniqueS as UniqueS2 on ProductS.BrandId=UniqueS2.Id ");
            sb.Append(" WHERE  ProductSInCheckStoreS.OrderNO='"+order.OrderNO+"'");

            List<TempFunction> obj = new List<TempFunction>();
            foreach (DataRow row in SQLdata.GetDataRows(sb.ToString()))
            {
                TempFunction tf = new TempFunction()
                {
                    ProductSId=(Int64)row["Id"],
                    BrandId=(Int64)row["BrandId"],
                    PlaceId=(Int64)row["PlaceId"],
                    GroupSId=(Int64)row["GroupSId"],
                    _QuantityOld = (double)row["QuantityOld"],
                    _QuantityNew=(double)row["QuantityNew"],
                    Name = row["Name"] as string,
                    Barcode = row["Barcode"] as string,
                    Code = row["Code"] as string,
                    _BrandName = row["BrandName"] as string,
                    _PlaceName = row["PlaceName"] as string,
                    _UnitName = row["UnitName"] as string,
                    Standard = row["Standard"] as string
                };
                productInList.Add(tf);
            }
            dataGridObject.IsReadOnly = false;
        }

        private void PanDianEnd()
        {
            if (order.Id == -1)
            {
                MessageWindow.Show("盘点未开始");
                return;
            }
            else if (order.Enable == Table.CheckStoreS.EnumEnable.盘点结束)
            {
                MessageWindow.Show("盘点已结束");
                return;
            }
            else if (MessageWindow.Show("", "盘点结束后无法编辑库存,是否继续?", MessageBoxButton.YesNo) == MessageBoxResult.Yes)
            {
                MessageWindow.Show(order.ShenHe().ToString());
                this.Close();
            }
        }

        private void Search()
        {
            switch (flag)
            {
                case Flag.开始盘点:
                    if (!string.IsNullOrEmpty(textBoxSearch.Text))
                    {
                        SearchText();
                        return;
                    }
                    var find = (IEnumerable<TempFunction>)productInList;
                    if (!string.IsNullOrEmpty(uCGroupS1.Text))
                        find = from f in find where f.GroupSId == uCGroupS1.SelectedObjectId select f;
                    if (!string.IsNullOrEmpty(uCUniqueSPlaceId.Text))
                        find = from f in find where f.PlaceId == uCUniqueSPlaceId.SelectedObjectId select f;
                    if (!string.IsNullOrEmpty(uCUniqueSBrandId.Text))
                        find = from f in find where f.BrandId == uCUniqueSBrandId.SelectedObjectId select f;

                    dataGridObject.ItemsSourceNoCalc = new ObservableCollection<TempFunction>(find);
                    break;

                case Flag.盘点准备单:
                    StringBuilder sb = new StringBuilder("SELECT  UniqueS.Name as UnitName,UniqueS1.Name as PlaceName,UniqueS2.Name as BrandName, ProductS.Code, ProductSInStoreS.Quantity, ProductS.Name, ProductS.Standard, ProductS.Barcode");
                    sb.Append(", ProductS.PlaceId FROM ProductS INNER JOIN");
                    sb.Append("  ProductSInStoreS ON  ProductS.Id = ProductSInStoreS.ProductSId left join UniqueS on ProductS.UnitId=UniqueS.Id ");
                    sb.Append(" left join UniqueS as UniqueS1 on ProductS.PlaceId=UniqueS1.Id left join UniqueS as UniqueS2 on ProductS.BrandId=UniqueS2.Id ");
                    sb.Append(" WHERE  (ProductS.Enable = 0)   AND  ProductSInStoreS.StoreSId =" + uCStoreS1.SelectedObjectId);
                    if (!string.IsNullOrEmpty(uCGroupS1.Text))
                        sb.Append(" and ProductS.GroupSId=" + uCGroupS1.SelectedValue);
                    if (!string.IsNullOrEmpty(uCUniqueSPlaceId.Text))
                        sb.Append(" and ProductS.PlaceId=" + uCUniqueSPlaceId.SelectedObjectId);
                    if (!string.IsNullOrEmpty(uCUniqueSBrandId.Text))
                        sb.Append(" and ProductS.BrandId=" + uCUniqueSBrandId.SelectedObjectId);

                    List<TempFunction> obj = new List<TempFunction>();
                    foreach (DataRow row in SQLdata.GetDataRows(sb.ToString()))
                    {
                        TempFunction tf = new TempFunction()
                        {
                            _QuantityOld = (double)row["Quantity"],
                            Name = row["Name"] as string,
                            Barcode = row["Barcode"] as string,
                            Code = row["Code"] as string,
                            _BrandName = row["BrandName"] as string,
                            _PlaceName = row["PlaceName"] as string,
                            _UnitName = row["UnitName"] as string,
                            Standard = row["Standard"] as string
                        };
                        obj.Add(tf);
                    }

                    dataGridObject.ItemsSourceNoCalc = obj;
                    break;
            }
        }

        private void Print()
        {
            switch (flag)
            {
                case Flag.开始盘点:
                    foreach (TempFunction p in productInList)
                        order.ProductSList.First(f => f.ProductSId == p.ProductSId).QuantityNew = p._QuantityNew.Value;

                    MessageWindow.Show(order.Update().ToString());
                    break;

                case Flag.盘点准备单:
                    PrintFunction.PrintList(dataGridObject.DataGrid, DataTableText.盘点单);
                    break;
            }
        }

        private void SearchText()
        {
            var find = from f in productInList where f.Name.Contains(textBoxSearch.Text) || f.Code.Contains(textBoxSearch.Text) || f.Barcode.Contains(textBoxSearch.Text) select f;
            dataGridObject.ItemsSourceNoCalc = new List<TempFunction>(find);
            textBoxSearch.Clear();
        }
    }

    public class TempFunction
    {
        public Int64 ProductSId { get; set; }
        public double _QuantityOld { get; set; }
        public double? _QuantityNew { get; set; }
        public string _PlaceName
        {
            get;
            set;
        }
        public string _BrandName
        {
            get;
            set;
        }
        public string Code
        {
            get;
            set;
        }
        public string Name
        {
            get;
            set;
        }
        public string Standard
        {
            get;
            set;
        }
        public string _UnitName
        {
            get;
            set;
        }
        public string Barcode
        {
            get;
            set;
        }
        public Int64 GroupSId { get; set; }
        public Int64 BrandId { get; set; }
        public Int64 PlaceId { get; set; }
    }
}